package org.ekstrabilet.search.gui;
import javax.swing.*;
import javax.swing.JSpinner.DateEditor;

import java.awt.*;
import java.sql.Date;
import java.sql.Time;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.*;

import org.ekstrabilet.game.beans.Game;
import org.ekstrabilet.game.logic.GameLogic;
import org.ekstrabilet.logic.exceptions.StadiumException;
import org.ekstrabilet.stadium.StadiumViewPane;
import org.ekstrabilet.stadium.logic.StadiumLogic;

/**  
 * Class provides component which is used to search games
 * and show scores of searching
 */
public class SearchPanel {
	
	JPanel mainSearchPane;
	JPanel searchPane ;
	private StadiumViewPane stadiumViewPane;
	private String[][] results;
	

	//Fields
	private JTextField taField;
	private JTextField tbField;
	private JComboBox snField;
	private JComboBox scField;	
	private DateChooser dateChooser;
	private TimeChooser timeChooser;
	
	//searchScores	
	private DefaultTableModel searchScoresModel;
	private JTable searchScores;
	private String[] columnNames = {"Home", "Visitors", "Stadium", "City", "Date", "Time"};
	private List<Game> searchResults;
	private JTableHeader header;
	private JScrollPane tablePane;
	
	//Labels
	private JLabel taLabel;
	private JLabel tbLabel;	
	private JLabel snLabel;
	private JLabel scLabel;	
	private JLabel dLabel;
	private JLabel tLabel;
	
	//Boxes
	Box teamBox ;
	Box stadiumBox ;
	Box dtBox ;
	Box scoreBox ;	
	
	
	//Button
	JButton searchButton ;
	
	public SearchPanel(){
		
		searchPane = new JPanel();
		mainSearchPane = new JPanel();
		
		
		//Labels
		taLabel = new JLabel("Team A:");
		tbLabel = new JLabel("Team B:");		
		snLabel = new JLabel("Stadium:");
		scLabel = new JLabel("City:");		
		dLabel = new JLabel("Date:");
		tLabel = new JLabel("Time:");
		
		//Fields
		taField = new JTextField();
		tbField = new JTextField();

		snField = new JComboBox(StadiumLogic.getInstance().getStadiumsArray(""));
		snField.setMaximumRowCount(10);
		scField = new JComboBox(StadiumLogic.getInstance().getCitiesArray(""));	
		scField.setMaximumRowCount(10);
		dateChooser = new DateChooser();
		timeChooser = new TimeChooser();		
		
						
		searchButton =  new JButton("Search");		
		searchButton.addActionListener(new SearchButtonListener(this));
		
		
		//Layout
		searchPane.setLayout(new BoxLayout(searchPane, BoxLayout.Y_AXIS));
		teamBox = Box.createHorizontalBox();
		stadiumBox = Box.createHorizontalBox();
		dtBox = Box.createHorizontalBox();
		scoreBox = Box.createVerticalBox();
		teamBox.setPreferredSize(new Dimension(400, 25));
		stadiumBox.setPreferredSize(new Dimension(400, 25));
		dtBox.setPreferredSize(new Dimension(400, 25));
		
		//search scores
		searchScoresModel = new DefaultTableModel(columnNames, 0);		
		searchScores = new JTable(searchScoresModel){
			  public boolean isCellEditable(int rowIndex, int colIndex) {
				  return false; //Disallow the editing of any cell
				  }};
		searchScores.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
			
			@Override
			public void valueChanged(ListSelectionEvent arg0) {
				//System.out.println(results[searchScores.getSelectedRow()][0]);
				//System.out.println(results[searchScores.getSelectedRow()][0]);
				if(searchScores.getSelectedRow() < 0) return;
				try {
					stadiumViewPane.setStadium(StadiumLogic.getInstance().
							getStadium(results[searchScores.getSelectedRow()][2],
									results[searchScores.getSelectedRow()][3]));
				} catch (StadiumException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}		
				//TODO
				//tutaj jest lipa
				Game g = searchResults.get(searchScores.getSelectedRow());
				//System.out.println(g.getGameID());
				stadiumViewPane.setGame(g);
			}
		});
		header = searchScores.getTableHeader();
		header.setBackground(Color.WHITE);
		
	    tablePane = new JScrollPane(searchScores);
	    tablePane.revalidate();
	    tablePane.repaint();
		
		init();		
	}

	/**  
	* Return search panel
	 */
	public JPanel getPanel() {
		return mainSearchPane;
	}
	
	/**  
	 * Set StadiumViewPane to communicate with 
	 */
	public void setStadiumViewPane(StadiumViewPane stadiumViewPane) {
		this.stadiumViewPane = stadiumViewPane;
	}
	
	/**  
	 * initializes all elements of search panel component
	 */
	public void init(){
		scoreBox.add(header);
		scoreBox.add(tablePane, BorderLayout.SOUTH);
		
		
		teamBox.add(taLabel);
		teamBox.add(taField);
		teamBox.add(tbLabel);
		teamBox.add(tbField);
		
		stadiumBox.add(snLabel);
		stadiumBox.add(snField);
		stadiumBox.add(scLabel);
		stadiumBox.add(scField);
		
		dtBox.add(dLabel);
		dtBox.add(dateChooser.getDateChooser());
		dtBox.add(tLabel);
		dtBox.add(timeChooser.getTimeChooser());
		
		searchPane.add(teamBox);
		searchPane.add(stadiumBox);
		searchPane.add(dtBox);
		searchPane.add(searchButton);
		searchPane.add(scoreBox);	
		
		mainSearchPane.add(searchPane, BorderLayout.PAGE_START);		
	}
	
	/**  
	 * Returns GameBean that represents data for searching
	 */
	public Game getSearchData(){		

		return  new Game(taField.getText(), tbField.getText(), snField.getSelectedItem().toString(), scField.getSelectedItem().toString(), Date.valueOf(dateChooser.getSqlDate().toString()), Time.valueOf(timeChooser.getSqlTime().toString()));
		

	}
	
	/**  
	 * Print search scores in JTable
	 */
	public void showSearchResults(){
		
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");		   
		java.util.Date date = new java.util.Date();

		if (dateFormat.format(date).compareTo(getSearchData().getGameDate().toString()) > 0){
			Object[] options = {"Yes", "No"};
			int n = JOptionPane.showOptionDialog(mainSearchPane, "You have asked for past games, are You sure?", "Past date" ,
			JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
			null, options, options[1]);
			if (n == 1){
				return;
			}			
		}	 
		List<Game> newSearchResults = GameLogic.getInstance().searchGames(getSearchData());	
		if (newSearchResults.equals(searchResults)){
			return;
		}
		else {
			
			searchScoresModel.setRowCount(0);
			results = new String[newSearchResults.size()][6];
			
			for (int i = 0; i < newSearchResults.size(); ++i){
				results[i][0]=newSearchResults.get(i).getTeamA();
				results[i][1]=newSearchResults.get(i).getTeamB();
				results[i][2]=newSearchResults.get(i).getStadiumName();
				results[i][3]=newSearchResults.get(i).getStadiumCity();
				results[i][4]=newSearchResults.get(i).getGameDate().toString();
				results[i][5]=newSearchResults.get(i).getGameTime().toString();			
			}	
			for (int i=0; i<newSearchResults.size(); ++i){

				searchScoresModel.addRow(results[i]);
			}
			searchResults = newSearchResults; 
					
			scoreBox.revalidate();	
		}
	}

}
